package com.ftg.learn.chapter09.reflech.demo03.ioc;

import java.util.Arrays;
import java.util.Objects;

/**
 * 功能编写处
 *
 * @author kangjx
 * @date 2023/1/13
 */
public class BeanFactoryImpl implements BeanFactory {

    /**
     * 容器 ： 里面存储的是啥 资源 {别名  实例}
     */
    private NaturalResources[] res;

    private int index = 0;

    private int default_size = 10;

    @Override
    public void putBeanIntoContainers(DetailList list) {
        if(Objects.isNull(res)){
            res = new NaturalResources[default_size];
        }

        if(this.index == this.res.length){
           this.res = Arrays.copyOf(this.res,this.res.length >> 1 + this.res.length);
        }

        //判断 如果有相同的 别名 报错
        res[index++] = detailListConverntToResources(list);
    }

    @Override
    public void putBeanIntoContainers(DetailList[] list) {
        if(list == null){
            throw new RuntimeException("请给我清单");
        }
        for (DetailList detailList : list) {
            putBeanIntoContainers(detailList);
        }
    }

    @Override
    public Object getBean(String aliasName) {

        if(this.index == 0){
            throw new RuntimeException("请先为容器，添加资源，请提供你的清单");
        }

        for (int i = 0; i < this.index; i++) {
            if(this.res[i].getAliasName().equals(aliasName)){
                return this.res[i].getInstance();
            }
        }
        return null;
    }
}
